// @before-stub-for-debug-begin
#include <vector>
#include <string>
#include <numeric>
#include "commoncppproblem227.h"

using namespace std;
// @before-stub-for-debug-end

/*
 * @lc app=leetcode.cn id=227 lang=cpp
 *
 * [227] 基本计算器 II
 */

// @lc code=start
class Solution {
public:
    int calculate(string s) {
        vector<int> stk;
        int size = s.size();
        int num = 0;
        char sign = '+';               // 数的正反，1为正，
        for(int i = 0 ; i < size; i++)
        {
            
            // 处理数字
            if(s[i] >= '0')
            {
                while(s[i] >='0' && s[i] <= '9' && i < size)
                {
                    num = num * 10 + s[i] - '0';
                    i++;
                }
                i--;
            }
            if(s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/')
            {
                
                // 处理 "+"
                if(sign == '+')
                {
                    stk.push_back(num);
                    num = 0;
                    sign = s[i];
                    continue;
                }

                // 处理 “-”
                if(sign == '-')
                {
                    stk.push_back(-num);
                    num = 0;
                    sign = s[i];
                    continue;
                }

                // 处理 “*”
                if(sign == '*')
                {
                    stk.back() *= num;
                    num = 0;
                    sign = s[i];
                    continue;
                }

                // 处理"/
                if(sign == '/')
                {
                    stk.back() /= num;
                    num = 0;
                    sign = s[i];
                    continue;
                }
            }
        }
        return accumulate(stk.begin(), stk.end(), 0);
    }

/*
    int calculate(string s) {
        vector<int> stk;
        char preSign = '+';
        int num = 0;
        int n = s.length();
        for (int i = 0; i < n; ++i) {
            if (isdigit(s[i])) {
                num = num * 10 + int(s[i] - '0');
            }
            if (!isdigit(s[i]) && s[i] != ' ' || i == n - 1) {
                switch (preSign) {
                    case '+':
                        stk.push_back(num);
                        break;
                    case '-':
                        stk.push_back(-num);
                        break;
                    case '*':
                        stk.back() *= num;
                        break;
                    default:
                        stk.back() /= num;
                }
                preSign = s[i];
                num = 0;
            }
        }
        return accumulate(stk.begin(), stk.end(), 0);
    }
*/

};
// @lc code=end

